package com.liaoct.lct.adapter;

import java.util.List;
import java.util.Map;
import com.liaoct.lct.activity.R;
import com.liaoct.lct.listener.ContactListItemClickListener;
import com.liaoct.lct.util.Constant;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * 联系人列表适配器
 * 
 * @author liaoct
 * 
 */
public class ContactListViewAdapter extends BaseAdapter {

	/**
	 * 上下文
	 */
	private Context context;

	private List<Map<String, Object>> data;

	private String[] from;

	private int[] to;

	/**
	 * 布局加载器
	 */
	private LayoutInflater inflater;

	public ContactListViewAdapter(Context context,
			List<Map<String, Object>> data, String[] from, int[] to) {
		this.context = context;
		this.data = data;
		this.from = from;
		this.to = to;
		this.inflater = (LayoutInflater) this.context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	@Override
	public int getCount() {
		return data.size();
	}

	@Override
	public Object getItem(int position) {
		return data.get(position);
	}

	@Override
	public long getItemId(int position) {

		return position;
	}

	public void refresh(List<Map<String, Object>> data) {
		this.data = data;
		this.notifyDataSetChanged();
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View v;
		if (convertView == null) {
			v = inflater.inflate(R.layout.list_view_row, null);
		} else {
			v = convertView;
		}
		v.setOnClickListener(new ContactListItemClickListener(context,
				Constant.CONTACT_ITEM_CLICK_INFO));
		this.bindData(position, v);
		return v;
	}

	private void bindData(int position, View view) {
		Map<String, Object> map = data.get(position);
		if (map == null) {
			return;
		}
		for (int i = 0; i < this.from.length; i++) {
			String key = from[i];
			Object value = map.get(key);
			View v = view.findViewById(this.to[i]);
			if (v instanceof TextView) {
				TextView text = (TextView) v;
				text.setText(value == null ? "" : value.toString());
			} else if (v instanceof ImageView) {
				ImageView image = (ImageView) v;
//				image.setBackgroundResource(Integer.parseInt(value.toString()));
				image.setOnClickListener(new ContactListItemClickListener(
						context, Constant.CONTACT_ITEM_CLICK_DIAL));
			}
		}
	}

}
